package com.coder.bike.utils;


import com.coder.bike.vo.RouteVO;
import org.springframework.beans.BeanUtils;
import com.coder.bike.entity.Permission;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class RouteTreeUtils {
    /**
     * 基于权限列表和父权限ID构建路由树。
     *
     * @param permissionList 权限列表，包含所有路由的权限信息。
     * @param pid 父权限ID，用于筛选特定父级下的路由。
     * @return 返回一个路由树的列表，每个路由包含路径、名称、组件等信息，以及可能的子路
    由。
     */
    public static List<RouteVO> buildRouteTree(List<Permission> permissionList, int pid) {
        List<RouteVO> routeVOList = new ArrayList<>();

        // 筛选当前层级的菜单（pid匹配）
        List<Permission> currentLevelPermissions = permissionList.stream()
                .filter(p -> p != null && p.getPid() == pid)
                .collect(Collectors.toList());

        for (Permission permission : currentLevelPermissions) {
            RouteVO routeVO = new RouteVO();
            routeVO.setPath(ensurePathFormat(permission.getRoutePath()));
            routeVO.setName(permission.getRouteName());
            routeVO.setComponent(pid == 0 ? "Layout" : permission.getRouteUrl());
            routeVO.setAlwaysShow(pid == 0);

            // 设置Meta信息
            RouteVO.Meta meta = routeVO.new Meta(
                    permission.getPermissionLabel(),
                    permission.getIcon(),
                    new String[]{permission.getPermissionCode()}
            );
            routeVO.setMeta(meta);

            // 递归构建子菜单
            List<RouteVO> children = buildRouteTree(permissionList, permission.getId());
            routeVO.setChildren(children);

            routeVOList.add(routeVO);
        }

        return routeVOList;
    }

    private static String ensurePathFormat(String routePath) {
        return routePath.startsWith("/") ? routePath : "/" + routePath;
    }
    public static List<Permission> buildMenuTree(List<Permission> list,int
            pid){
        List<Permission> menuList = new ArrayList<>();
        Optional.ofNullable(list).orElse(new ArrayList<>())
                .stream()
                .filter(permission -> permission != null &&
                        permission.getPid() == pid)
                .forEach(permission -> {
                    Permission menu = new Permission();
                    BeanUtils.copyProperties(permission,menu);
                    menu.setChildren(buildMenuTree(list,permission.getId()));
                    menuList.add(menu);
                });
        return menuList;
    }


}